import { app } from "../../App";

export class WebSocketClient {
    public static instance: WebSocketClient = new WebSocketClient();

    public _socket: WebSocket = null;
    public connected: boolean = false;
    public uuid: string = "";

    public heartEnabled: boolean = true; //是否开启心跳
    private heartInterval = 5000; //心跳间隔时间
    public lastHeartTime = 0; //心跳超时计数
    private serverTimer; //服务器超时定时器
    public isRelease: boolean = false; //是否是正式环境

    /**
     * 收到服务器消息
     * @param e
     */
    public onReceiveMessage(event: MessageEvent): void {}

    private _socketID: number = 1000;

    /**
     * 开始Socket连接
     */
    public connect(
        wsUrl: string,
        _onOpen: () => void,
        _onMessage: (msg: MessageEvent) => void,
        _onClose: (event: CloseEvent) => void,
        _onError: (evt: Event) => void
    ): void {
        if (this._socket) {
            if (this._socket.readyState === WebSocket.CONNECTING) {
                app.log.error("websocket connecting, wait for a moment...");
                return;
            }
        }
        this._socket = new WebSocket(wsUrl);
        this._socketID += 1;
        this._socket.binaryType = "arraybuffer";
        this._socket.onopen = _onOpen;
        this._socket.onclose = _onClose;
        this._socket.onerror = _onError;
        this._socket.onmessage = _onMessage;
    }

    /**
     * 发送消息到服务器
     * @param message
     * @param commandId
     */
    public sendMessage(message: any, commandId: number): void {}

    public sendBinaryMessage(messageBuffer: ArrayBuffer): void {
        this._socket?.send(messageBuffer);
    }
    /**
     * 清理当前的Socket连接
     */
    public closeCurrentSocket(log: number = 0) {
        this.reset();
        if (this._socket) {
            this._socket.close();
        }
        this._socket = null;
        this.connected = false;
    }

    /**
     * 开启心跳
     * @param func
     */
    public startHeartBeat(func: Function) {
        this.serverTimer = setTimeout(() => {
            func();
            //函数执行完后，重置定时器
            this.serverTimer = setTimeout(func, this.heartInterval);
        }, this.heartInterval);
    }

    // 重置心跳定时器/服务超时定时器
    public reset() {
        this.lastHeartTime = 0;
        this.serverTimer && clearTimeout(this.serverTimer);
    }

    // WebSocket连接状态
    public onReady(): boolean {
        if (this._socket && this.connected && this._socket.readyState === WebSocket.OPEN) {
            return true;
        }
        return false;
    }

    public setPlayerUUID(uuid: string) {
        this.uuid = uuid;
    }
}
